package com.example.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.exception.CustomException;
import com.example.mapper.MessageMapper;
import com.example.mapper.OrderMapper;
import com.example.mapper.RoomMapper;
import com.example.mapper.UserMapper;
import com.example.pojo.Message;
import com.example.pojo.Order;
import com.example.pojo.PageResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private UserMapper userMapper;

    // 分页获取消息
    public PageResult<Order> getOrders(Integer userId, String role,
                                       Integer page, Integer pageSize,
                                       String status,String roomName) {
        // 1. 构建分页参数
        Page<Order> pageParam = new Page<>(page, pageSize);

        // 2. 执行分页查询
        IPage<Order> pageResult = orderMapper.selectByUserOrOwner(pageParam, userId, role,status,roomName);

        // 3. 封装分页结果（与图片中的消息分页结构一致）
        return new PageResult<>(
                (int) pageResult.getTotal(),
                pageResult.getRecords()
        );
    }


    public Integer insert(Order order) {
        order.setCreateTime(new Date());
        order.setStatus("0");//待房东确认状态
        int res =orderMapper.insert(order);
        if (res <= 0){
            throw new CustomException("500","订单创建失败");
        }
//        Message message  = new Message();
//        message.setReceiverId(order.getOwnerId());
//        message.setReceiverType("owner");
//        message.setType("system-order");
//        message.setTypeId(order.getId());
//        message.setContent("用户："+order.getUserName()+"预约了您的房间："+order.getRoomName()+"，请及时处理");
//        message.setStatus("0");
//        message.setCreateTime(new Date());
        String userName = userMapper.selectById(order.getUserId()).getName();
        String roomName = roomMapper.selectById(order.getRoomId()).getName();
        Message message = new Message(
                "owner",
                order.getOwnerId(),
                "system-order",
                order.getId(),
                "用户："+userName+"下单了您的房间："+roomName+"，请及时处理"
                );
        messageMapper.insert(message);
        return res;
    }

    public void cancelOrder(Integer orderId) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        // WHERE id = orderId
        updateWrapper.eq("id", orderId)
                .set("status", "4");
        //执行更新（参数1为null表示不更新实体对象，仅通过wrapper设置更新内容
        int updateRes = orderMapper.update(null, updateWrapper);
        if (updateRes <= 0){
            log.error("订单取消失败，报错函数：cancelOrder,订单id:"+orderId);
            throw new CustomException("500","订单取消失败");
        }
        // 更新房间状态为空闲
        Integer roomId = orderMapper.selectById(orderId).getRoomId();
        roomMapper.updateStatus(roomId,"0");
        String roomName = roomMapper.selectById(roomId).getName();
        log.info("订单 {} 取消成功，房间 {} 状态已更新为可预订", orderId, roomName);
    }

    public void pay(Integer orderId) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();

        updateWrapper.eq("id", orderId) // WHERE id = orderId
                .eq("status", "0") // 当前状态必须为待支付（0）
                .set("status", "1");
        int res = orderMapper.update(null, updateWrapper);
        if (res == 0) {
            // 两种情况会触发异常：
            // 1. 订单不存在
            // 2. 当前状态不是0
            log.error("订单状态错误，无法支付");
            throw new CustomException("500","订单状态错误，无法支付");
        }

        //支付成功后更新房间状态
        Order order = orderMapper.selectById(orderId);
        roomMapper.updateStatus(order.getRoomId(),"1");

    }

    public void confirmOrder(Integer orderId) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();

        updateWrapper.eq("id", orderId) // WHERE id = orderId
                .eq("status", "1") // 当前状态必须为已支付（1）
                .set("status", "2");
        int res = orderMapper.update(null, updateWrapper);
        if (res == 0) {
            // 两种情况会触发异常：
            // 1. 订单不存在
            // 2. 当前状态不是1
            log.error("订单状态错误，无法确认");
            throw new CustomException("500","订单状态错误，无法确认");
        }
    }

    public void checkIn(Integer orderId) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();

        updateWrapper.eq("id", orderId) // WHERE id = orderId
                .eq("status", "2") // 当前状态必须为房东已确认（2）
                .set("status", "3");
        int res = orderMapper.update(null, updateWrapper);
        if (res == 0) {
            // 两种情况会触发异常：
            // 1. 订单不存在
            // 2. 当前状态不是3
            log.error("订单状态错误，无法入住，请联系房东");
            throw new CustomException("500","订单状态错误，无法入住，请联系房东");
        }
    }

    public List<Order> selectAllByStatusAndTime(String status,int timeoutSeconds) {
        // 计算超时时间点（当前时间 - 超时秒数）
        LocalDateTime timeoutTime = LocalDateTime.now().minusSeconds(timeoutSeconds);

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("status", status)
                .lt("create_time", timeoutTime);
        return orderMapper.selectList(wrapper);
    }
}